package com.example.bee_work_3.fragment.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.swipe.SwipeLayout;
import com.example.bee_work_3.R;
import com.example.bee_work_3.account.LoginActivity;
import com.example.bee_work_3.account.LoginOrRegister;
import com.example.bee_work_3.account.RegisterActivity;
import com.example.bee_work_3.collect.ListActivity;
import com.example.bee_work_3.fragment.ListItem;
import com.example.bee_work_3.net_request.MyJsonArray;
import com.example.bee_work_3.net_request.MyJsonObject;
import com.example.bee_work_3.net_request.WS;
import com.example.bee_work_3.webc_ontent.IntentCallBack;
import com.example.bee_work_3.webc_ontent.WebActivity;

import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

@SuppressLint("ValidFragment")
public class Fragment_home extends Fragment implements View.OnClickListener {
    //普通变量
    private final int LOGIN = 0;
    private final int REGISTER = 1;
    private final int UPDATE = 2;
    private final int PICTURE = 3;
    private static int pager = 0;
    static boolean isRefresh = true;
    private int lastItem = 0;
    private boolean move = false;//是否正在切换底层view

    //控件实例
    private SwipeRefreshLayout swipeRefreshLayout;
    private SwipeLayout swipeLayout;
    private RelativeLayout myCollection;
    private RecyclerView recyclerView;
    private Button login, register, logout;
    private TextView name;

    //数据、适配器
    private List<ListItem> itemList = new ArrayList<>();
    private List<ListItem> pictureList = new ArrayList<>();
    private PicturePagerAdapter picturePagerAdapter;
    private com.example.bee_work_3.fragment.home.ItemAdapter ItemAdapter;

    //用到的类实例
    private LoginOrRegister loginOrRegister;
    private MyJsonObject mUser;
    private Context mContext;

    //回调接口一类
    private WS.CallBack callBack = new WS.CallBack() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onResult(String Json) {
            mUser = new MyJsonObject(Json);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    name.setText(mUser.getJsonObject("data").getString("username"));
                }
            });
        }
    };
    public IntentCallBack intentCallBack = new IntentCallBack() {
        @Override
        public void onIntent(ListItem item) {
            Intent intent = new Intent(getContext(), WebActivity.class);
            intent.putExtra("URL", item.getLink());
            intent.putExtra("title", item.getText());
            intent.putExtra("id", item.getId());
            startActivity(intent);
        }

    };
    /**public PictureCarousel carousel = new PictureCarousel() {
        @Override
        public void onChange(final ViewPager viewPager, final int count) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (swipeLayout.getSurfaceView() == swipeLayout.getCurrentBottomView()){
                        Log.e("suface","on");
                    }
                    if (move)
                        viewPager.setCurrentItem(count);
                }
            });
        }
    };**/
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE:
                    ItemAdapter.notifyDataSetChanged();
                    break;
                case PICTURE:
                    picturePagerAdapter.notifyDataSetChanged();
                    isRefresh = true;
                    ItemAdapter.notifyDataSetChanged();
                    if (swipeRefreshLayout.isRefreshing())
                        swipeRefreshLayout.setRefreshing(false);
                    break;
            }
            return true;
        }
    });

    @SuppressLint("ValidFragment")
    public Fragment_home(Context context) {
        this.mContext = context;
    }

    @Override
    public void onCreate(Bundle savedInstanceStace) {
        super.onCreate(savedInstanceStace);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        init(view);
        return view;
    }

    public void init(View view) {
        //个人信息卡片
        login = getActivity().findViewById(R.id.btn_login);
        register = getActivity().findViewById(R.id.btn_register);
        logout = getActivity().findViewById(R.id.btn_logout);
        name = getActivity().findViewById(R.id.name);
        myCollection = getActivity().findViewById(R.id.myCollection);
        swipeRefreshLayout = view.findViewById(R.id.home_refresh);
        swipeLayout = getActivity().findViewById(R.id.swipe_layout);

        logout.setOnClickListener(this);
        login.setOnClickListener(this);
        view.findViewById(R.id.info).setOnClickListener(this);
        register.setOnClickListener(this);
        swipeRefreshLayout.setColorSchemeColors(Color.GREEN, Color.YELLOW, Color.BLUE);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                itemList.clear();
                pictureList.clear();
                pager = 0;
                refresh("https://www.wanandroid.com/banner/json");
                loading("https://www.wanandroid.com/article/list/" + (pager++) + "/json");
            }
        });

        picturePagerAdapter = new PicturePagerAdapter(intentCallBack, pictureList, getActivity());
        ItemAdapter = new ItemAdapter(R.layout.listitem, itemList, picturePagerAdapter, intentCallBack);
        refresh("https://www.wanandroid.com/banner/json");
        loading("https://www.wanandroid.com/article/list/" + (pager++) + "/json");
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView = view.findViewById(R.id.home_list);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(ItemAdapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //滑动到最后位置时加载新的数据
                if (newState == recyclerView.SCROLL_STATE_IDLE && lastItem + 1 == ItemAdapter.getItemCount()) {
                    //refresh("https://www.wanandroid.com/banner/json");
                    loading("https://www.wanandroid.com/article/list/" + (pager++) + "/json");
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //找到最后一个位置
                lastItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        getWeather("重庆");
        loginOrRegister = new LoginOrRegister(getActivity().getSharedPreferences("user_data", MODE_PRIVATE), callBack);
        if (loginOrRegister.autoLogin()) {
            //如果本地有数据则自动登录
            Toast.makeText(getContext(), "已自动登录", Toast.LENGTH_SHORT).show();
            logout.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
        }
        myCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ListActivity.class);
                intent.putExtra("title", "我的收藏");
                startActivity(intent);
            }
        });
    }

    //刷新置顶文章
    public void refresh(String url) {
        WS.load(url)
                .addCallBack(new WS.CallBack() {
                    @Override
                    public void onResult(String Json) {
                        Log.e("json",Json);
                        MyJsonObject temp = new MyJsonObject(Json);
                        if (!temp.getString("errorCode").equals("0")) {
                            Toast.makeText(mContext, "加载失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        MyJsonArray JsonArray = temp.getJsonArray("data");
                        List<MyJsonObject> list = JsonArray.getList();
                        for (MyJsonObject t : list) {
                            ListItem r = new ListItem(t.getString("title"), t.getString("imagePath")
                                    , t.getString("url"),"ss","ss",t.getBoolean("collect"), t.getInt("id"));
                            pictureList.add(r);
                        }
                        Message msg = Message.obtain();
                        msg.what = PICTURE;
                        handler.sendMessage(msg);
                    }
                })
                .get();
    }

    //上拉加载
    public void loading(String url) {
        WS.load(url)
                .addCallBack(new WS.CallBack() {
                    @Override
                    public void onResult(String Json) {
                        MyJsonObject temp = new MyJsonObject(Json);
                        if (temp.getInt("errorCode") != 0) {
                            Toast.makeText(mContext, "加载失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        MyJsonArray JsonArray = temp.getJsonObject("data").getJsonArray("datas");
                        List<MyJsonObject> list = JsonArray.getList();
                        int count = itemList.size();
                        for (MyJsonObject t : list) {
                            ListItem r = new ListItem(t.getString("title"), null, t.getString("link")
                                    , t.getString("niceDate"),t.getString("author"),t.getBoolean("collect"),t.getInt("id"));
                            itemList.add(r);
                        }
                        if (count == 0) {
                            return;
                        }
                        Message msg = Message.obtain();
                        msg.what = UPDATE;
                        handler.sendMessage(msg);
                    }
                })
                .get();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                startActivityForResult(new Intent(getActivity(), LoginActivity.class), LOGIN);
                break;
            case R.id.btn_register:
                startActivityForResult(new Intent(getActivity(), RegisterActivity.class), REGISTER);
                break;
            case R.id.btn_logout:
                name.setText("请登录...");
                login.setVisibility(View.VISIBLE);
                logout.setVisibility(View.GONE);
                break;
            case R.id.info:
                Log.e("swipe","on"+swipeLayout.getShowMode());
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                swipeLayout.onTouchEvent(MotionEvent.obtain(10,10,MotionEvent.ACTION_DOWN,100,100,0));
                                swipeLayout.onTouchEvent(MotionEvent.obtain(10,10,MotionEvent.ACTION_MOVE,200,100,0));
                                swipeLayout.onTouchEvent(MotionEvent.obtain(10,10,MotionEvent.ACTION_MOVE,300,100,0));
                                swipeLayout.onTouchEvent(MotionEvent.obtain(10,10,MotionEvent.ACTION_MOVE,500,100,0));
                                swipeLayout.onTouchEvent(MotionEvent.obtain(10,10,MotionEvent.ACTION_UP,600,100,0));
                                Log.e("swipe","on"+swipeLayout.getShowMode());
                            }
                        });
                    }
                }).start();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case LOGIN:
                if (resultCode != RESULT_OK)
                    break;
                Toast.makeText(getActivity().getApplicationContext(), data.getStringExtra("username") + "登录成功", Toast.LENGTH_SHORT).show();
                logout.setVisibility(View.VISIBLE);
                login.setVisibility(View.GONE);
                name.setText(data.getStringExtra("username"));
                break;
            case REGISTER:
                if (requestCode != RESULT_OK)
                    break;
                Toast.makeText(getActivity().getApplicationContext(), data.getStringExtra("username") + "登录成功", Toast.LENGTH_SHORT).show();
                logout.setVisibility(View.VISIBLE);
                login.setVisibility(View.GONE);
                name.setText(data.getStringExtra("username"));
                break;
        }
    }

    public void getWeather(String city) {
        WS.load("https://www.apiopen.top/weatherApi?city=" + city)
                .addCallBack(new WS.CallBack() {
                    @Override
                    public void onResult(String Json) {
                        final MyJsonObject myJsonObject = new MyJsonObject(Json);
                        if (myJsonObject.getInt("code") != 200)
                            return;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TextView temp = getActivity().findViewById(R.id.weather_temperature);
                                TextView notice = getActivity().findViewById(R.id.weather_notice);
                                TextView type = getActivity().findViewById(R.id.weather_type);
                                MyJsonObject data = myJsonObject.getJsonObject("data");
                                MyJsonObject today = data.getJsonArray("forecast").get(0);
                                temp.setText(data.getInt("wendu") + "℃");
                                notice.setText(data.getString("ganmao"));
                                type.setText(today.getString("type") + "\n" + today.getString("fengxiang"));
                            }
                        });
                    }
                })
                .get();
    }

}
